﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;

namespace Pegasus.Runtime.Serialization
{
	/// <summary>
	/// This class is used to serialize and deserialize an objet (or whole object graph).
	/// </summary>
	public static class ObjectSerializer
	{
		/// <summary>
		/// Serialize an Object to XML via the <see cref="System.Runtime.Serialization.NetDataContractSerializer"/>.
		/// </summary>
		/// <param name="obj">The object to serialize.</param>
		/// <returns>The XML string</returns>
		public static string ObjectToXml( object obj )
		{
			using( MemoryStream memStream = new MemoryStream() )
			{
				NetDataContractSerializer serializer = new NetDataContractSerializer();
				serializer.WriteObject( memStream, obj );

				memStream.Flush();
				return UTF8Encoding.UTF8.GetString( memStream.GetBuffer(), 0, (int) memStream.Position );
			}
		}

		/// <summary>
		/// Deserialize XML to an Object via the <see cref="System.Runtime.Serialization.NetDataContractSerializer"/>.
		/// </summary>
		/// <param name="xml">The XML to deserialize.</param>
		/// <returns>The orginal object.</returns>
		public static object XmlToObject( string xml )
		{
			// TODO: Need to support pegasus version 2.0 xml serialization.
			object obj = null;
			
			byte[] xmlData = UTF8Encoding.UTF8.GetBytes( xml );
			using( MemoryStream memStream = new MemoryStream( xmlData ) )
			{
				NetDataContractSerializer serializer = new NetDataContractSerializer();
				obj = serializer.ReadObject( memStream );
			}

			return obj;
		}
	}
}
